package com.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.config.SentinelConfig;
import com.example.service.NacosService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

@RestController
@RefreshScope
@RequestMapping("/providers")
public class Consume {
    @Autowired
    private NacosService nacosService;
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping(value = {"/consume/{username}/{age}",
            "/consume/{username}",
               "/consume"})
    @SentinelResource(value = "blockConsume",blockHandlerClass = SentinelConfig.class,
            blockHandler = "sentinelBlock")
    public String consume(@PathVariable(value = "username",required = false) String username,
                          @PathVariable(value = "age",required = false) Integer age){
        if(age==1){
                throw new RuntimeException("4124");
        }
        String provider = nacosService.provider(username,age);
        return provider;
    }
    public String fallbackHandle(String username,Integer age){
        return "我是fallback方法";
    }
    public String consumeBlock(String username,Integer age,BlockException e){
        return "O(∩_∩)O/(ㄒoㄒ)/~~名字"+username;
    }
    @GetMapping("/httpconsume/{username}/{age}")
    public String httpConsume(@PathVariable(value = "username",required = false) String username,
                              @PathVariable(value = "age",required = false) Integer age){
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://nacos-provider/provider/"+username+"/"+age, String.class);
        return forEntity.getBody().toString()+"status"+forEntity.getStatusCodeValue();
    }
    @GetMapping("/consume/c")
    @SentinelResource(value = "c",blockHandler = "blockC")
    public String consume1(@RequestParam(value = "name",required = false)String name){
        return "关联链路测试"+name;
    }
    public String blockC(String name, BlockException e){
        return "blockc"+name;
    }

    @GetMapping("/consumeteachers")
    public String consumeTeacher(){
        System.out.println("11312");
        String teachers = nacosService.teachers();
        System.out.println(teachers);
        return teachers;
    }
    @GetMapping("/teachers")
    public String teacher(){
        return "consume3000O(∩_∩)O";
    }
}
